from flask import request, jsonify, send_file
from src.api.controllers.search_controller import SearchController
from src.database.dao.upload_file_dao import UploadedFile, UploadedFileDAO
from src.utils.logger import log_info
from src.config import OUTSITE_VIDEO_DIR, SPECIAL_ROOT_DIR_ORIGIN
import os
from starlette.responses import FileResponse
from urllib.parse import unquote

def register_search_routes(bp):
    controller = SearchController()
    
    @bp.route('/search/matched_videos', methods=['POST'])
    def search_videos():
        data = request.json
        prompt_data = data.get('prompt_data', [])  # Expect an array of [idx, category, text] items
        start_date = data.get('start_date', None)
        end_date = data.get('end_date', None)
        results = []
        # Iterate through the prompt_data array
        for idx, category, text, max_duration in prompt_data:
            log_info(f"接收到搜索请求: 索引={idx}, 分类={category}, 关键词={text}")
            
            # Search for each prompt entry
            result = controller.search_videos(
                category=category,
                query=text,
                max_duration=max_duration,
                start_date=start_date,
                end_date=end_date
            )
            
            # Add index to result for client-side matching
            result['idx'] = idx
            result['category'] = category
            results.append(result)
        return {"success": True, "data": results}
    
    @bp.route('/search/categories', methods=['GET'])
    def get_categories():
        log_info("接收到获取分类列表请求")
        result = controller.get_categories()
        return jsonify(result)
    
    @bp.route('/search/test', methods=['POST'])
    def get_test():
        data = request.json
        
        return jsonify(data)
    
    
    @bp.route('/search/update-index', methods=['POST'])
    def update_search_index():
        log_info("接收到更新搜索索引请求")
        result = controller.update_search_index()
        return jsonify(result)
    
    
    @bp.route('/search/audio_group', methods=['GET'])
    def get_audio_group():
        log_info("接收到获取音频组请求")
        group_id = request.args.get('group_id')
        result = controller.get_group_audio(group_id=group_id)
        return result
    
    @bp.route('/search/audio_history', methods=['GET'])
    def get_audio_history():
        """获取音频历史记录，支持分页"""
        log_info("接收到获取音频历史记录请求")
        
        # 从请求参数获取分页信息，默认第1页，每页10条
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        
        # 调用控制器方法
        result = controller.get_audio_history(page, page_size)
        return jsonify(result)

    @bp.route('/search/video_history', methods=['GET'])
    def get_video_history():
        """获取视频历史记录，支持分页"""
        log_info("接收到获取视频历史记录请求")
        
        # 从请求参数获取分页信息，默认第1页，每页10条
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        
        # 调用控制器方法
        result = controller.get_video_history(page, page_size)
        return jsonify(result)
    
    
    @bp.route('/search/transition_effects', methods=['GET'])
    def get_transition_effects():
        """获取所有可用的转场效果"""
        log_info("接收到获取转场效果请求")
        effects = controller.get_transition_effects()
        return jsonify({"success": True, "data": effects})

    @bp.route('/search/suggest_tags', methods=['GET'])    
    def get_suggest_tags():
        """搜索标签"""
        query = request.args.get('query', '')
        category = request.args.get('category', '')
        limit = request.args.get('limit', 10, type=int)
        
        log_info(f"接收到搜索标签请求: 关键词={query}, 限制={limit}")
        result = controller.get_suggest_tags(category, query, limit)
        return jsonify(result)
    
        
    @bp.route('/search/outside_video/<path:file_path>', methods=['GET'])
    def get_file(file_path):
        """
        获取指定路径的文件
        
        支持多级路径如: 1级/2级/te.mp4
        
        Args:
            file_path: 请求的文件路径，相对于OUTSITE_VIDEO_DIR
        
        Returns:
            文件响应或错误信息
        """
        file_path = unquote(file_path)  # 解码URL编码的路径
        log_info(f"接收到文件访问请求: 路径={file_path}")
        
        if file_path.startswith('\\\\'):
            # 如果路径以斜杠开头，移除前导斜杠
            return send_file(file_path)
        
        # 防止路径遍历攻击，移除任何尝试访问上级目录的部分
        if '..' in file_path:
            return jsonify({"success": False, "message": "无效的文件路径"}), 400
        
        # 构建完整的文件路径
        full_path = os.path.join(OUTSITE_VIDEO_DIR , file_path.replace('/', '\\').lstrip('/\\'))
        log_info(f"请求的完整文件路径: {full_path}")
        # 检查文件是否存在
        if not os.path.exists(full_path) or not os.path.isfile(full_path):
            log_info(f"{full_path}")
            return jsonify({"success": False, "message": "文件不存在"}), 404
        
        try:
            return send_file(full_path)
        except Exception as e:
            log_info(f"文件访问错误: {e}")
            return jsonify({"success": False, "message": f"访问文件时发生错误: {e}"}), 500
        
        
    @bp.route('/search/intro_outro_videos', methods=['GET'])
    def get_intro_outro_videos():
        """获取可用的片头片尾视频列表"""
        video_type = request.args.get('type')
        
        # 调用控制器方法获取视频列表
        result = controller.get_intro_outro_videos(video_type)
        return jsonify(result)